package com.gdut.simple.data.remote.http.core;

import android.util.Log;

import com.gdut.simple.basic.BasicApplication;
import com.gdut.simple.common.NetworkUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class HttpCore {

    private OkHttpClient mHttpClient;

    private volatile static HttpCore mInstance;

    private static final long CONNECTED_TIMEOUT = 20000;
    private static final long READ_TIMEOUT = 15000;
    private static final long WRITE_TIMEOUT = 20000;

    private static final int DEFAULT_CACHE_SIZE = 1024 * 1024 * 20;
    private static final int DEFAULT_MAX_AGE = 60 * 60;
    private static final int DEFAULT_MAX_STALE_ONLINE = DEFAULT_MAX_AGE * 24;
    private static final int DEFAULT_MAX_STALE_OFFLINE = DEFAULT_MAX_AGE * 24 * 7;

    private static final Interceptor REQUEST_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            int maxStale = DEFAULT_MAX_STALE_ONLINE;
            // 向服务器请求数据缓存1小时
            CacheControl tempCacheControl = new CacheControl.Builder()
                    .maxStale(maxStale, TimeUnit.SECONDS)
                    .build();
            request = request.newBuilder()
                    .cacheControl(tempCacheControl)
                    .build();
            return chain.proceed(request);
        }
    };

    private static final Interceptor RESPONSE_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response originalResponse = chain.proceed(request);
            int maxAge;
            if (!NetworkUtils.isConnected(BasicApplication.getApplication())) {
                maxAge = DEFAULT_MAX_STALE_OFFLINE;
            } else {
                maxAge = DEFAULT_MAX_STALE_ONLINE;
            }
            return originalResponse.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public,max-age=" + maxAge)
                    .build();
        }
    };

    private static final Interceptor LOGGER_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            long t1 = System.nanoTime();
            Log.i("Http", String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
            Response response = chain.proceed(request);
            long t2 = System.nanoTime();
            Log.i("Http", String.format("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers()));
            return response;
        }
    };

    static HttpCore getInstance() {
        if (mInstance == null) {
            synchronized (HttpCore.class) {
                if (mInstance == null) {
                    mInstance = new HttpCore();
                }
            }
        }
        return mInstance;
    }

    private HttpCore() {
        File cacheFile = new File(BasicApplication.getApplication().getCacheDir(), "responses");
        Cache cache = new Cache(cacheFile, DEFAULT_CACHE_SIZE);
        mHttpClient = new OkHttpClient.Builder()
                .cache(cache)
                .addInterceptor(REQUEST_INTERCEPTOR)
                .addNetworkInterceptor(RESPONSE_INTERCEPTOR)
                .addInterceptor(LOGGER_INTERCEPTOR)
                .connectTimeout(CONNECTED_TIMEOUT, TimeUnit.MILLISECONDS)
                .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
                .writeTimeout(WRITE_TIMEOUT, TimeUnit.MILLISECONDS)
                .build();
    }

    OkHttpClient getHttpClient() {
        return mHttpClient;
    }
}
